#!/usr/bin/env bash
set -e

export buildType="${1}"

cangjieTarget="aarch64-linux-android31"
cangjieFeatures="feature.env.android"
export ANDROID_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/android"
export ANDROID_NDK_DIR="${ANDROID_SDK_ROOT}/ndk/26.3.11579264"
os_name=$(uname -s)
if [ "$os_name" = "Linux" ]; then
    export SYSTEM_STRING="linux-x86_64"
else
    export SYSTEM_STRING="darwin-x86_64"
fi
export ANDROID_CANGJIE_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-android"
export ANDROID_PACKAGE="../../../../../package/target/aarch64-linux-android31/${buildType}/pkgnative_windows"

if [[ "${buildType}" == "debug" ]]; then
    cangjieExtraArgs="-g"
else
    cangjieExtraArgs=""
fi

source "$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-android/envsetup.sh"
cjpm build --no-feature-deduce --enable-features="${cangjieFeatures}" --target="${cangjieTarget}" ${cangjieExtraArgs}

outputDir="../../../libs/arm64-v8a"
mkdir -p "${outputDir}"
soFilePath="./target/${cangjieTarget}/${buildType}/javacallcj/libjavacallcj.so"

if [[ ! -f "${soFilePath}" ]]; then
    echo "Error: Cannot find output library at ${soFilePath}" >&2
    exit 1
fi

cp "${soFilePath}" "${outputDir}/"
